package com.example.day1203_newsport.proveder;


import com.bumptech.glide.Glide;
import com.example.day1203_newsport.ResourceTable;
import com.example.day1203_newsport.bean.Data;
import ohos.agp.components.*;

import java.util.List;


public class NewsListProvider extends BaseItemProvider {


    private List<Data> mDatas;

    @Override
    public int getCount() {
        return mDatas == null ? 0 : mDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return mDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder;
        Component tmp = component;
        if (tmp == null) {
            tmp = LayoutScatter.getInstance(componentContainer.getContext()).parse(ResourceTable.Layout_item_news_page, null, false);
            viewHolder = new ViewHolder();
            viewHolder.textNewsTitle = tmp.findComponentById(ResourceTable.Id_news_title);
            viewHolder.textDate = tmp.findComponentById(ResourceTable.Id_news_date);
            viewHolder.imgAvatar = tmp.findComponentById(ResourceTable.Id_img_avatar);
            tmp.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) tmp.getTag();
        }

        Data data = mDatas.get(position);
        viewHolder.textNewsTitle.setText(data.getTitle());
        viewHolder.textDate.setText(data.getDate());
        String thumbnail_pic_s = data.getThumbnail_pic_s();

        Glide.with(componentContainer.getContext())
                .load(thumbnail_pic_s)
                .into(viewHolder.imgAvatar);

        return tmp;
    }

    public void setData(List<Data> data) {
        if (data != null && data.size() > 0) {
            mDatas = data;
            //刷新provider
            notifyDataChanged();
        }
    }

    private class ViewHolder {
        Text textNewsTitle;
        Text textDate;
        Image imgAvatar;
    }
}
